package fibertest

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"

	"gitee.com/daledi/public/vmap"
	"github.com/gofiber/fiber"
)

func HttpTest(method, uri string, payload interface{}, headers map[string]string, app *fiber.App) {
	var req *http.Request
	if payload != nil {
		data, _ := json.Marshal(payload)
		fmt.Printf("%s\n", string(data))
		body := bytes.NewReader(data)
		req, _ = http.NewRequest(method, uri, body)
	} else {
		req, _ = http.NewRequest(method, uri, nil)
	}

	if method != "GET" {
		req.Header.Set("Content-Type", "application/json")
	}
	for k := range headers {
		req.Header.Set(k, headers[k])
	}
	resp, err := app.Test(req, 1000*60)
	if err != nil {
		fmt.Printf("Error: %+v\n", err)
	} else {
		cl, _ := strconv.Atoi(resp.Header.Get("Content-Length"))
		fmt.Printf("cl: %d\n", cl)
		ct := resp.Header.Get("Content-Type")

		if cl > 0 {
			buf, _ := ioutil.ReadAll(resp.Body)
			if strings.Contains(ct, "application/json") {
				FormatOut(buf)
			} else {
				fmt.Printf("body: %s\n", string(buf))
			}
		}
	}
}

// FormatOut 将body按json格式输出
func FormatOut(body []byte) {
	var tt vmap.V
	if err := json.Unmarshal(body, &tt); err != nil {
		fmt.Printf("err: %v", err)
	}
	cc, _ := json.MarshalIndent(tt, "", "  ")
	fmt.Printf("Body: %s", string(cc))
}
